<template>
  <inline-Modal :visible="visible">
    <div class="annotationsListPage-container">
      <div class="screen-conditions-container">
        <ScreenConditions :isDataType="false">
          <template slot="conditions">
            <a-tree-select
              class="project-select"
              v-model="condition.contentsId"
              show-search
              placeholder="请选择目录名称"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              tree-default-expand-all
              :loading="condition.treeLoading"
              treeNodeFilterProp="title"
              :replaceFields="{
                children: 'children',
                title: 'nodeName',
                key: 'uuid',
                value: 'id',
              }"
              :tree-data="treeData"
              @change="changeContents"
            >
            </a-tree-select>
            <a-select
              placeholder="请选择图纸名称"
              v-model="condition.cadFileUuid"
            >
              <a-select-option
                :value="item.uuid"
                v-for="item in drawingSource"
                :key="item.uuid"
              >
                {{ item.fileName }}
              </a-select-option>
            </a-select>
            <a-input
              v-model="condition.issueName"
              placeholder="请输入问题名称"
            ></a-input>
            <a-select
              placeholder="请选择问题类型"
              v-model="condition.issueType"
            >
              <a-select-option
                :value="item.dicItemCode"
                v-for="item in issueTypeSoucre"
                :key="item.dicItemCode"
              >
                {{ item.dicItemName }}
              </a-select-option>
            </a-select>
            <a-select
              placeholder="请选择问题等级"
              v-model="condition.issueGrade"
            >
              <a-select-option
                :value="item.dicItemCode"
                v-for="item in issueGradeSoucre"
                :key="item.dicItemCode"
              >
                {{ item.dicItemName }}
              </a-select-option>
            </a-select>
            <a-range-picker
              format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD"
              v-model="condition.date"
              :show-time="false"
              :placeholder="['期望修改开始日期', '期望修改结束日期']"
            />
          </template>
          <template slot="operate">
            <a-button class="cu-btn-primary" icon="search" @click="search()">
              查询
            </a-button>
            <a-button class="cu-btn-filter" icon="reload" @click="reset()">
              重置
            </a-button>
            <!-- <a-button
              class="cu-btn-primary submit-button"
              v-if="isButton"
              @click="handleSubmit()"
            >
              提交
            </a-button> -->
            <a-button class="back-button" @click="goBack()">返回</a-button>
          </template>
        </ScreenConditions>
      </div>
      <div class="card-container">
        <a-row :gutter="[10, 0]">
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
            <div class="card-dom">
              <div class="icon"></div>
              <div class="warp">
                <div class="name">问题总数</div>
                <div class="money">
                  {{ Number(statisticsSource.allCount || 0).toLocaleString()
                  }}<span>个</span>
                </div>
              </div>
            </div>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
            <div class="card-dom">
              <div class="icon" ref="pie_1"></div>
              <div class="warp">
                <div class="name">已处理数</div>
                <div class="money">
                  {{ Number(statisticsSource.yclCount || 0).toLocaleString()
                  }}<span>个</span>
                </div>
              </div>
            </div>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
            <div class="card-dom">
              <div class="icon" ref="pie_2"></div>
              <div class="warp">
                <div class="name">未处理数</div>
                <div class="money">
                  {{ Number(statisticsSource.wclCount || 0).toLocaleString()
                  }}<span>个</span>
                </div>
              </div>
            </div>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
            <div class="card-dom">
              <div class="icon" ref="pie_3"></div>
              <div class="warp">
                <div class="name">处理率</div>
                <div class="money">
                  {{ Number(statisticsSource.radio || 0).toLocaleString()
                  }}<span>%</span>
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>
      <div class="annotationsListPage-body">
        <div class="annotation-table-list">
          <vxe-table
            ref="xTable"
            height="99%"
            align="center"
            show-overflow
            show-header-overflow
            border="inner"
            :data="tableData"
            :column-config="{ resizable: true }"
            size="small"
            :loading="loading"
          >
            <vxe-column type="seq" width="80" title="序号"></vxe-column>
            <vxe-column field="cadName" title="图纸名称" align="left">
            </vxe-column>
            <vxe-column field="cadCode" title="图纸编号" align="left">
            </vxe-column>
            <vxe-column field="issueName" title="问题名称" align="left">
            </vxe-column>
            <vxe-column field="issueDesc" title="问题描述" align="left">
            </vxe-column>
            <vxe-column field="creator" title="提交人"> </vxe-column>
            <vxe-column field="creatorOrg" title="提交单位"> </vxe-column>
            <vxe-column field="createTime" title="提交时间"> </vxe-column>
            <vxe-column title="图片">
              <template #default="{ row }">
                <div class="files-icon">
                  <a-tooltip placement="top">
                    <template slot="title">
                      预览
                    </template>
                    <a-icon type="eye" @click="previewImg(row)" />
                  </a-tooltip>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="remark" title="备注"> </vxe-column>

            <vxe-column title="状态" width="100">
              <template #default="{ row }">
                <div
                  class="state"
                  :class="[filterStateClass(row.approveStatus)]"
                >
                  {{ filterStateName(row.approveStatus) }}
                </div>
              </template>
            </vxe-column>

            <vxe-column
              field="operate"
              width="160"
              title="操作"
              fixed="right"
              align="left"
            >
              <template #default="{ row }">
                <div class="text-button-group">
                  <!--  -->
                  <a-tooltip placement="top">
                    <template slot="title">
                      查看
                    </template>
                    <a-icon type="file-search" @click="handleDetail(row)" />
                  </a-tooltip>
                  <!--  -->
                  <a-tooltip v-if="row.deal">
                    <template slot="title">
                      处理
                    </template>
                    <icon-fonts
                      icon="icon-zhenggaicuoshi"
                      class="contrast"
                      @change="handleProblem(row, 1)"
                    ></icon-fonts>
                  </a-tooltip>
                  <!-- 审批记录 -->
                  <a-tooltip placement="top" v-if="row.approveRecord">
                    <template slot="title">
                      审批记录
                    </template>
                    <icon-fonts
                      icon="icon-shenpi"
                      class="record"
                      @change="gotoApprovalRecord(row)"
                    ></icon-fonts>
                  </a-tooltip>
                  <!-- 审批 -->
                  <a-tooltip placement="top" v-if="row.approve">
                    <template slot="title">
                      审批
                    </template>
                    <icon-fonts
                      icon="icon-shenpi1"
                      class="approve"
                      @change="handleProblem(row, 3)"
                    ></icon-fonts>
                  </a-tooltip>
                  <!-- 编辑  -->
                  <a-tooltip v-if="row.edit">
                    <template slot="title">
                      编辑
                    </template>
                    <a-icon type="edit" @click="handleEdit(row)" />
                  </a-tooltip>
                  <!-- 删除  -->
                  <a-tooltip v-if="row.del">
                    <template slot="title">
                      删除
                    </template>
                    <a-icon type="delete" @click="handleDelClick(row)" />
                  </a-tooltip>
                </div>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <div class="table-pager">
          <vxe-pager
            size="small"
            background
            :current-page.sync="pager.page"
            :page-size.sync="pager.pageSize"
            :total="pager.total"
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
            :page-sizes="[20, 50, 100, 500]"
            @page-change="paginationChange"
          >
            <template #left>
              <div class="vxe-pager-left-tip-container">
                共<span>{{ pager.total }}</span
                >条
              </div>
            </template>
          </vxe-pager>
        </div>
      </div>
    </div>
    <!-- 详情 -->
    <detailAnnotationsModal
      :visible.sync="detailAnnotationsModal.visible"
      :parameter="detailAnnotationsModal.soucre"
    ></detailAnnotationsModal>
    <!-- 处理 -->
    <handleProblemModal
      :visible.sync="handleProblemModal.visible"
      :parameter="handleProblemModal.soucre"
      :operateType="handleProblemModal.operateType"
      :footer="handleProblemModal.footer"
      @onRefresh="getRefresh()"
    ></handleProblemModal>

    <!-- 预览图片 -->
    <viewImageModal
      :visible.sync="viewImageModal.visible"
      :parameter="viewImageModal.row"
    ></viewImageModal>

    <!-- 审批记录 -->
    <comment-modal ref="commentModal"></comment-modal>
  </inline-Modal>
</template>

<script>
//问题清单【列表】
import { axios } from "@/utils/request";
import echarts from "echarts";
import { addAttributeByKey } from "@/utils/util.js";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
//详情
import detailAnnotationsModal from "./detailAnnotationsModal.vue";
//处理问题
import handleProblemModal from "./handleProblemModal.vue";
//预览图片
import viewImageModal from "./viewImageModal.vue";
//审批记录
import commentModal from "@/pages/workflow/oaLeave/comment.vue";
import {
  pageAnnotations,
  deleteAnnotations,
  headerAnnotations,
  approveAnnotations,
} from "@/api/design";
import { getDicItemByCode } from "@/api/common.js";
export default {
  inject: ["drawingModel"],
  components: {
    ScreenConditions,
    detailAnnotationsModal,
    handleProblemModal,
    viewImageModal,
    commentModal,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //是否刷新最新的三条数据
    isRefresh: {
      type: Boolean,
      default: false,
    },
    //是的展示确定按钮
    isButton: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      //问题类型
      issueTypeSoucre: [],
      //问题等级
      issueGradeSoucre: [],
      pageModule: 7,
      //查询条件
      condition: {
        //目录id
        contentsId: undefined,
        //图纸名称
        cadFileUuid: undefined,
        //问题名称
        issueName: "",
        //问题类型
        issueType: undefined,
        //问题等级
        issueGrade: undefined,
        // 期望修改日期
        date: [],
      },
      //目录名称
      treeData: [],
      //图纸名称
      drawingSource: [],
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      chartInstance: {},
      //统计数据
      statisticsSource: {
        allCount: 0,
        radio: 0,
        wclCount: 0,
        yclCount: 0,
      },
      //详情
      detailAnnotationsModal: {
        visible: false,
        soucre: {},
      },
      //处理问题
      handleProblemModal: {
        visible: false,
        soucre: {},
        operateType: 1,
        footer: {},
      },
      //预览
      viewImageModal: {
        visible: false,
        row: {},
      },
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          Promise.all([
            this.getUploadTreeData(),
            this.getHeaderCard(),
            this.getTableData(),
            this.getData(),
          ]);
        }
      },
      immediate: true,
    },
  },
  methods: {
    async getData() {
      //问题类型
      this.issueTypeSoucre = await this.getDicCodeData("issueTypeSJ");
      //问题等级
      this.issueGradeSoucre = await this.getDicCodeData("issueGrade");
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    getRefresh() {
      this.getHeaderCard();
      this.getTableData();
    },

    handleSubmit() {
      let { uuid = "" } = this.drawingModel();
      let that = this;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定提交所选内容?",
        content: "",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FAAD14",
          }),
        onOk() {
          that.loading = true;
          approveAnnotations({
            uuid,
            operate: "2",
            reason: "同意",
          })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("提交成功", 1.5);
                that.getHeaderCard();
                that.getTableData();
                that.goBack();
              } else {
                that.$message.error(res?.message ?? "提交失败");
              }
            })
            .catch((_) => {
              that.$message.error(res?.message ?? "提交失败");
            })
            .finally(() => {
              that.loading = false;
            });
        },
        onCancel() {},
      });
    },

    //审批记录
    gotoApprovalRecord(record) {
      this.$refs.commentModal.getCommentList(record.uuid);
    },

    //预览图片
    previewImg(row) {
      this.viewImageModal.row = row;
      this.viewImageModal.visible = true;
    },

    search() {
      this.pager.page = 1;
      this.getHeaderCard();
      this.getTableData();
    },

    reset() {
      this.condition.cadFileUuid = undefined;
      this.condition.issueName = "";
      this.condition.issueType = undefined;
      this.condition.issueGrade = undefined;
      this.condition.date = [];
      this.search();
    },

    //选择目录
    changeContents() {
      this.condition.cadFileUuid = undefined;
      this.handleUploadTable();
    },

    //查询目录名称
    getUploadTreeData() {
      let { proCode, uuid = "", fileSource } = this.drawingModel();
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/drawingReview/getTreeByProCodeInner`,
            {
              proCode,
              uuid,
              type: this.pageModule,
              addClassifyIdLs: [],
              deleteClassifyIdLs: [],
              fileSource,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            let source = data ?? [];
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "children"
            );
            this.treeData = filterData;
            this.condition.contentsId = this.treeData?.[0]?.id ?? undefined;
            this.handleUploadTable();
            resolve();
          })
          .catch((_) => {
            this.condition.contentsId = undefined;
            this.treeData = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询图纸名称
    handleUploadTable() {
      let { contentsId } = this.condition;
      let { proCode, uuid = "" } = this.drawingModel();
      if (!proCode || !contentsId) {
        return;
      }
      axios
        .post(
          `/probusiness/bimCadFile/getListByForeignKey`,
          {
            classifyId: contentsId,
            proCode,
            type: this.pageModule,
            uuid,
            addFileIdLs: [],
            deleteFileIdLs: [],
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          this.drawingSource = data ?? [];
        })
        .catch((_) => {
          this.drawingSource = [];
        })
        .finally((_) => {});
    },
    //查询头部统计
    getHeaderCard() {
      let { uuid } = this.drawingModel();
      let { cadFileUuid = "", issueName } = this.condition;
      headerAnnotations({
        drawingReviewUuid: uuid,
        cadFileUuid,
        issueName,
      })
        .then((res) => {
          let { data } = res;
          this.statisticsSource = data ?? {};
          this.$nextTick(() => {
            let color_1 = ["#1677FF", "rgba(147, 164, 207, 0.30)"];
            let color_2 = ["#FF2D2D", "rgba(207, 147, 147, 0.30)"];
            let color_3 = ["#37C39A", "rgba(147, 207, 190, 0.30)"];
            //已处理
            this.drawPieChar(
              "pie_1",
              this.statisticsSource.yclCount,
              this.statisticsSource.allCount,
              color_1,
              require("./images/icon_2.png")
            );
            //未处理
            this.drawPieChar(
              "pie_2",
              this.statisticsSource.wclCount,
              this.statisticsSource.allCount,
              color_2,
              require("./images/icon_3.png")
            );
            //处理率
            this.drawPieChar(
              "pie_3",
              this.statisticsSource.radio,
              100,
              color_3,
              require("./images/icon_4.png")
            );
          });
        })
        .catch((_) => {
          this.statisticsSource = {
            allCount: 0,
            radio: 0,
            wclCount: 0,
            yclCount: 0,
          };
        });
    },

    //查询列表数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let {
        cadFileUuid = "",
        issueName,
        issueType = "",
        issueGrade = "",
        date,
      } = this.condition;
      let { uuid } = this.drawingModel();
      return new Promise((resolve, reject) => {
        pageAnnotations({
          page,
          pageSize,
          drawingReviewUuid: uuid,
          cadFileUuid,
          issueName,
          issueType,
          issueGrade,
          startTime: date?.[0] ?? "",
          endTime: date?.[1] ?? "",
        })
          .then((res) => {
            this.tableData = res.data?.rows || [];
            this.pager.total = res.data?.totalCount || 0;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //编辑
    handleEdit(row) {
      this.$emit("editorView", row);
      this.goBack();
    },

    //查看
    handleDetail(row) {
      this.detailAnnotationsModal.soucre = row;
      this.detailAnnotationsModal.visible = true;
    },

    //处理
    handleProblem(row, type) {
      this.handleProblemModal.operateType = type;
      this.handleProblemModal.soucre = row;
      this.handleProblemModal.footer = {};
      this.handleProblemModal.visible = true;
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          deleteAnnotations({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //统计图
    drawPieChar(refName, number, max, color, icon) {
      if (!refName) {
        return;
      }

      let chart_dom = this.$refs[refName];
      this.chartInstance[refName] && this.chartInstance[refName].dispose();
      let instance = echarts.init(chart_dom);
      this.chartInstance[refName] = instance;
      let baseOpt = {
        tooltip: {
          show: false,
        },
        graphic: {
          elements: [
            {
              type: "image",
              z: 6,
              style: {
                image: icon,
                width: 20,
                height: 20,
              },
              left: "center",
              top: "center",
            },
          ],
        },
        polar: {
          radius: ["75%", "98%"],
        },
        angleAxis: {
          //   max: max - number,
          max: max,
          show: false,
        },
        radiusAxis: {
          type: "category",
          show: true,
          axisLabel: {
            show: false,
          },
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
        color: color[0],
        series: [
          {
            name: "",
            type: "bar",
            roundCap: true,
            barWidth: 60,
            showBackground: true,
            backgroundStyle: {
              color: color[1],
            },
            data: [number],
            coordinateSystem: "polar",
          },
        ],
      };
      instance.setOption(baseOpt);
      //开启响应式
      window.addEventListener("resize", () => {
        instance.resize();
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },

    //返回
    goBack() {
      this.$emit("update:visible", false);
      if (this.isRefresh) {
        this.$emit("refreshThree");
      } else {
        this.$parent.getTableData();
      }
    },
    filterStateName(val) {
      switch (val) {
        case 0:
          return "待提交";
        case 1:
          return "审批中";
        case 2:
          return "审批通过";
        case 3:
          return "驳回";
        case 4:
          return "待处理";
        default:
          return "-";
      }
    },

    filterStateClass(val) {
      switch (val) {
        case 0:
          return "default";
        case 1:
          return "ing";
        case 2:
          return "lock";
        case 3:
          return "error";
        case 4:
          return "deal";
        default:
          return "";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.modal-full-layout {
  background-color: #f0f2f5;
  /deep/.header {
    display: none;
  }
  /deep/.main {
    padding: 0;
    overflow: hidden !important;
  }
  .annotationsListPage-container {
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .screen-conditions-container {
      .conditions-screening-container {
        padding-right: 200px;
      }

      .more {
        cursor: pointer;
        font-size: 14px;
        color: #1890ff;
        margin-left: 10px;
        padding-top: 6px;
        .anticon {
          font-size: 12px;
        }
      }
    }

    .back-button {
      position: absolute;
      right: 16px;
    }
    .submit-button {
      position: absolute;
      right: 86px;
    }

    .card-container {
      padding: 0 0 10px 0;
      box-sizing: border-box;
      .card-dom {
        height: 120px;
        padding: 0 32px;
        box-sizing: border-box;
        background: @base-bg-color;
        border-radius: 6px 6px 6px 6px;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .icon {
          width: 88px;
          height: 88px;
        }

        .warp {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding-left: 16px;
          box-sizing: border-box;
          .name {
            font-size: 14px;
            color: #666666;
          }
          .money {
            font-size: 40px;
            color: #333333;
            span {
              font-size: 14px;
              color: #666666;
            }
          }
        }
      }
      /deep/.ant-row {
        :nth-child(1) {
          .card-dom {
            .icon {
              background: url("./images/icon_1.png") no-repeat center;
              background-size: 100% 100%;
            }
          }
        }
      }
    }

    .annotationsListPage-body {
      border-radius: 6px 6px 6px 6px;
      flex: 1;
      background-color: @base-bg-color;
      flex-shrink: 0;
      position: relative;
      padding: 10px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      .annotation-table-list {
        flex: 1;
        .files-icon {
          /deep/.anticon {
            cursor: pointer;
            font-size: 18px;
            color: #1677ff;
            margin-right: 16px;
            &:last-of-type {
              margin-right: 0;
            }
          }

          /deep/.anticon-download {
            color: #239b53;
          }

          /deep/.anticon-cloud-upload {
            color: #239b53;
          }
        }

        .state {
          &::before {
            position: relative;
            display: inline-block;
            content: "";
            width: 8px;
            height: 8px;
            background: #239b53;
            border-radius: 0px 0px 0px 0px;
            border-radius: 50%;
            margin-right: 10px;
          }
          &.default {
            &::before {
              background: #8c8c8c;
            }
          }
          &.ing {
            &::before {
              background: #f07f17;
            }
          }
          &.lock {
            &::before {
              background: #239b53;
            }
          }

          &.error {
            &::before {
              background: #ff3f4a;
            }
          }

          &.deal {
            &::before {
              background: #c652f0;
            }
          }
        }
      }
    }
  }
}
</style>
